package web.controller.admin;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import web.common.Result;
import web.service.CommonService;
import web.utils.CommonConvertUtils;
import web.utils.FileUtil;
import web.utils.JwtUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    CommonService commonService;

    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    @Qualifier("redisTemplate_15_verfiyCode") // 指定注入redisTemplate15
    private RedisTemplate redisTemplate_15_verfiyCode;

    private static final int CAPTCHA_EXPIRATION_TIME = 5 * 60 * 1000; // 验证码过期时间为5分钟


    /***
     * 获取界面结构的json接口
     * @return json
     * @throws IllegalAccessException
     * @throws IntrospectionException
     * @throws InvocationTargetException
     */
    @GetMapping("/initJson")
    public Map<String, Object> list(@RequestParam("mydx_token")String mydx_token) throws IllegalAccessException, IntrospectionException, InvocationTargetException {

        String account;
        try {
            Claims claims = JwtUtil.parseJWT(mydx_token);
            account = (String)claims.getSubject();
        } catch (Exception e) {
            return new HashMap<>();
        }

        HashMap<String, Object> initJson = commonService.getInitJson(account);

//        String jsonStr = FileUtil.readJsonFile("initjson/originData.json");
//        JSONObject josnObj = (JSONObject) JSON.parse(jsonStr);
//        Map res = CommonConvertUtils.convertBeanToMap(josnObj);
//        Map res2 = (Map) res.get("innerMap");
        return initJson;
    }

    @GetMapping("/getTemplate")
    public void getTemplate(@PathParam("tp") String tp, HttpServletResponse resp) {
        String path = "";
        switch (tp) {
            case "user":
                path = "static/ExcelTemplates/用户导入模板.xlsx";
            default:
//                throw new RuntimeException("参数异常");
        }
        String fileName = path.substring(path.lastIndexOf("/") + 1);
        try {
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //- 获取到下载到的文件的输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
        //- 创建一个缓冲区用来写入流
        int len = 0;
        byte[] bytes = new byte[1024];
        //- 获取OutputStream对象
        ServletOutputStream outputStream = null;
        try {
            outputStream = resp.getOutputStream();//- 将FileOutputStream对象的流写入到先前创建的buffer缓冲区中,使用OutputStream对象将buffer缓冲区中的数据输出到自己的客户端中
            while ((len = in.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否开启验证码功能
     * @return Result
     */
    @GetMapping("/captcha-require")
    public Result captchaRequire(
    ) {
        Result res = commonService.captchaRequire();
        return res;
    }

    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response,@RequestParam("serial")String serial) throws Exception {
        // 生成验证码图片
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(141,40,5,25);
        // 将验证码存入Redis中，并设置过期时间
//        redisTemplate_15_verfiyCode.opsForValue().set("captcha_" + request.getSession().getId(), captcha.getCode(), CAPTCHA_EXPIRATION_TIME, TimeUnit.MILLISECONDS);
        redisTemplate_15_verfiyCode.opsForValue().set("captcha_" + serial, captcha.getCode(), CAPTCHA_EXPIRATION_TIME, TimeUnit.MILLISECONDS);
        //        redisTemplate15.opsForValue().set("captcha_" + request.getSession().getId(), captcha.getCode(), CAPTCHA_EXPIRATION_TIME, TimeUnit.MILLISECONDS);
        // 将验证码图片输出给前端
        response.setContentType("image/png");
        captcha.write(response.getOutputStream());
    }
}
